# 用户类
# 实例属性：预算,用户名，密码，购物车
# 实例方法：
import pickle
import logging.config
import json

with open('logging_config.json', 'rt') as f:
    config = json.load(f)

logging.config.dictConfig(config)

logger = logging.getLogger('app')


class User():
    def __init__(self, name, passwd, init_amount):
        self.name = name
        self.passwd = passwd
        self.init_amount = init_amount
        self.shopping_car = {}


# 购物系统类
# 实例属性：商品信息，系统说明信息，当前用户--多个用户
# 方法：登录，注册，查看商品，添加购物车，结算
class ShoppingSystem():
    def __init__(self, goods_info, sys_info):
        self.goods_info = goods_info
        self.sys_info = sys_info
        self.userdict = {}

    def load_user(self):
        file_name = self.sys_info + "_user.pickle"
        # 忽略异常，不做任何事情
        try:
            with open(file_name, "rb") as fp:
                self.userdict = pickle.load(fp)
        except:
            pass

    def register(self, name, passwd, initial_amount):
        if name not in self.userdict:
            # 创建一个新用户，实例化User类
            user = User(name, passwd, initial_amount)
            logger.info(f"用户{name}注册成功")
            # 把名字作为key，user对象作为value，存在self.userdict里面
            self.userdict[name] = user
            file_name = self.sys_info + "_user.pickle"
            # tmp_dict = {}
            # for k,v in self.userdict.items():
            #     tmp_dict[k] = {"passwd": v.passwd, "init_amount": v.init_amount}
            with open(file_name, "wb") as fp:
                pickle.dump(self.userdict, fp)


        else:
            print("用户已存在")

    def login(self, name, passwd):
        if name in self.userdict and passwd == self.userdict[name].passwd:
            #添加日志功能
            logger.info(f"用户{name}登录成功")
            return True

    def view_goods(self):
        print("商品编号".ljust(10, " "), "商品名字".ljust(10, " "), "商品价格".ljust(10, " "))
        for key in self.goods_info:
            product_name = self.goods_info[key]["name"]
            product_price = self.goods_info[key]["price"]
            print(f"{key}".ljust(13, " "), f"{product_name}".ljust(13, " "), f"{product_price}")

    # dic[i] = dic.get(i, 0) + 1

    def add_shop(self, username, goods_id, num):
        user = self.userdict[username]
        if goods_id in user.shopping_car:
            user.shopping_car[goods_id]["count"] = user.shopping_car[goods_id].get("count") + num
        else:
            user.shopping_car[goods_id] = self.goods_info[goods_id]
            user.shopping_car[goods_id]["count"] = num
        print(user.shopping_car)

    def check(self, username):
        sum = 0
        user = self.userdict[username]
        user.init_amount = int(user.init_amount)
        for i in user.shopping_car:
            sum += (user.shopping_car[i]["price"] * user.shopping_car[i]["count"])
        print(f"商品金额为{sum}元")
        if user.init_amount < sum:
            print("余额不足")
        else:
            user.init_amount -= sum
            print(f"购买成功，余额剩{user.init_amount}元")
            logger.info(f"用户{username}购买成功，余额还剩{user.init_amount}元")




fruit_goods = {
    'F0001': {"name": "苹果", "price": 8},
    'F0002': {"name": "香蕉", "price": 4}
}

medicine_goods = {
    'M0001': {"name": "奥司他韦", "price": 60},
    'M0002': {"name": "抗病毒口服液", "price": 30}
}

system1 = ShoppingSystem(fruit_goods, "水果购物系统")
system2 = ShoppingSystem(medicine_goods, "药品购物")

system = [system1, system2]

while 1:
    print("当前平台，已有购物系统如下：")
    for k, v in enumerate(system):
        print(f"{k}.{v.sys_info}")
    c1 = input("请输入你的选择(按q退出)：")
    if c1 == "q":
        break
    if c1.isdigit() and int(c1) < len(system):
        c1 = int(c1)
        current_system = system[c1]
        current_system.load_user()
        print(f"欢迎进入{current_system.sys_info}".center(40, "*"))
        while 1:
            c2 = input("1.登录\n2.注册\n请输入你的选择(按q退出)")
            if c2 =="q":
                break
            if c2 == "1":
                username = input("请输入账号")
                passwd = input("请输入密码")
                if current_system.login(username, passwd):
                    while 1:
                        c3 = input("1.查看商品信息\n2.添加购物车\n3.结算购物车\n4.退出")
                        print("*" * 40)
                        if c3 == "1":
                            current_system.view_goods()
                        elif c3 == "2":
                            goods_id = input("请输入想添加的商品号:")
                            while 1:
                                num = int(input("请输入想购买的数量"))
                                if num > 0:
                                    print("当前购物车有以下商品：")
                                    current_system.add_shop(username, goods_id, num)
                                    break
                        elif c3 == "3":
                            current_system.check(username)
                        elif c3 == "4":
                            break
                else:
                    print("登录失败！请重新登录")
            elif c2 == "2":
                name, passwd, amount = input("请输入你的名字、密码、和初始金额(用空白分割)").split()
                current_system.register(name, passwd, amount)
                print(f"当前系统用户有:{current_system.userdict}")
            else:
                print("输入有误！")
    else:
        print("输入有误，请重新输入!")


